import React, { useMemo, useState } from "react";
import {
    Divider,
    Empty,
} from 'antd'
import './style.less'
import { ResultHeader } from "@/components/DataFlow/common/ResultHeader";
import { useCurrentNode } from "@/hooks/useCurrentNode";
import { useNodesData, useReactFlow } from "@xyflow/react";
import { RESULT_SHOW_MODE_DICT } from "@/constant/icons";
import { AggregateResultField } from "./AggregateResultField";
import { AggregateResultData } from "./AggregateResultData";
import { motion } from 'motion/react'
import { randomUUID } from "@/utils/dataflow";

export const AggregateResult = () => {
    const currentNode = useCurrentNode()
    const nodeData = useNodesData(currentNode?.id)
    const { updateNodeData } = useReactFlow()
    const [searchValue, setSearchValue] = useState('')
    const [showMode, setShowMode] = useState(RESULT_SHOW_MODE_DICT.field)

    const { allColumns: dataSource, columns, groupFields } = nodeData?.data || {};

    const searchResult = useMemo(() => {
        if (!searchValue) return dataSource
        return dataSource?.filter(s => s.columnName?.indexOf(searchValue) > -1)
    }, [dataSource, searchValue])

    const handleSelectionChange = (items) => {
        // 将当前选中的项转换为Set以便快速查找
        const selectedNames = new Set(items);

        let finalColumns;

        if (searchValue) {
            // 当有搜索值时，我们需要:
            // 1. 保留不在searchResult中的现有列
            // 2. 更新在searchResult中的列（根据当前选择状态）

            // 获取searchResult中的所有列名
            const searchResultNames = new Set(
                searchResult?.map(col => col.columnId) || []
            );

            // 分为两部分处理：
            // 1. 保留不在searchResult中的现有列
            const columnsOutsideSearch = (columns || []).filter(
                col => !searchResultNames.has(col.columnId)
            );

            // 2. 处理searchResult中的列 - 只保留被选中的
            const columnsFromSearch = (searchResult || []).filter(
                col => selectedNames.has(col.columnId)
            );

            // 合并两部分
            finalColumns = [...columnsOutsideSearch, ...columnsFromSearch];
        } else {
            // 没有搜索值时，直接用所有选中的列
            finalColumns = dataSource?.filter(d => selectedNames.has(d.columnId)) || [];
        }
        // 更新节点数据
        updateNodeData(currentNode?.id, { columns: finalColumns });
    };

    const handleChange = (row) => {
        const fieldMapper = (field) => {
            return field.columnId === row.columnId ? { ...row } : field
        }
        const updatedAllColumns = dataSource?.map(fieldMapper)
        const updatedColumns = columns?.map(fieldMapper)
        updateNodeData(currentNode?.id, { allColumns: updatedAllColumns, columns: updatedColumns })
    }

    const selectedRowKeys = useMemo(() => {
        return columns?.map(c => c.columnId)
    }, [columns])

    const renderContent = () => {
        if (showMode === RESULT_SHOW_MODE_DICT.data) {
            return <motion.div
                key="data"
                initial={{ opacity: 0, x: 10 }}
                animate={{ opacity: 1, x: 0 }}
                exit={{ opacity: 0, x: -10 }}
                transition={{ duration: 0.2 }}
            >
                <AggregateResultData />
            </motion.div >
        } else if (showMode === RESULT_SHOW_MODE_DICT.field) {
            return <motion.div
                key="field"
                initial={{ opacity: 0, x: 10 }}
                animate={{ opacity: 1, x: 0 }}
                exit={{ opacity: 0, x: -10 }}
                transition={{ duration: 0.2 }}
            >
                <AggregateResultField datasource={searchResult}
                    onSelectionChange={handleSelectionChange}
                    onChange={handleChange} selectedRowKeys={selectedRowKeys} />
            </motion.div>
        } else {
            return <motion.div
                key="default-empty"
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0 }}
                transition={{ duration: 0.2 }}
            >
                <Empty />
            </motion.div>
        }
    }

    return (
        <div className="aggregate-result-container">
            <ResultHeader info="聚合结果"
                total={dataSource?.length ?? 0}
                select={columns?.length ?? 0}
                mode={showMode}
                onChange={setShowMode}
                onSearch={setSearchValue}
            />
            <Divider style={{ margin: '8px 0' }} />
            <div className="aggregate-result-table">
                {
                    renderContent()
                }
            </div>
        </div>
    );
};